<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Random;
use phpCAS;
use think\Session;
use think\helper\Time;
use app\admin\model\Outsideschool as outside;
use think\Config;
use think\Db;
use app\admin\model\ReceptionUnit;
use think\Validate;

class Schoolfriend extends Frontend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = 'weiui';
    protected $model = null;

    public function _initialize(){
        parent::_initialize();
        $this->model = new outside();
    }

    public function index(){

        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if($params['tel']=='15911157463' || $params['nickname']=='郑养平' || $params['tel']=='15589850531' || $params['nickname']=='满学豪'){
                $this->error('你好，此用户不允许入校');
            }
	        $params['create_time'] = time();
        
            $params['applier_id'] = $params['applier_id'];
            $params['applier_name'] = $params['nickname'].'(校友)';
            // 匹配学院名称一致
            if($params['reception_name']=='经济学院（合作社学院）' || $params['reception_name']=='经济学院(合作社学院)' || $params['reception_name']=='经济管理学院(合作社学院)' ){
                $params['reception_name'] = '经济管理学院（合作社学院）';
            }
            if($params['reception_name']=='动物科技学院（草业学院）'){
                $params['reception_name'] = '动物科技学院';
            }
            if(empty($params['reception_name'])){
                $params['reception_name'] = '社会合作处';
            }
            $reception_info = ReceptionUnit::where(['name'=>['like', '%' . $params['reception_name'] . '%']])->find();
            if(!empty($reception_info)){
                $params['reception_id'] = $reception_info['id'];
                $params['reception_name'] = $reception_info['name'];
            }else{
                // 如果查找不到就统一给合作社
                $params['reception_id']   = 60;
                $params['reception_name'] = '社会合作处';
                $reception_info = ReceptionUnit::where(['id'=>60])->find();
            }
            if ($params['admission_starttime']){
                $params['admission_starttime'] = str_replace('/', '', $params['admission_starttime']);
                $s_date = date('Ymd');
                $day_total = floor((strtotime($params['admission_starttime'])-strtotime($s_date))/86400);
                if($day_total<2){
                    $this->error('温馨提示：为便于学院审核信息，请提前两天提交预约申请。');
                }
                $params['admission_endtime'] = $params['admission_starttime'];
            }
            if(isset($params['work_unit'])){
                if($params['work_unit']=='无' || $params['work_unit']=='没有'){
                    $this->error('请正确填写工作单位');
                }
            }
            if(!empty($params['card'])){
                if($params['card']!=$params['card_id']){
                    $this->error('注册身份证和填写身份证不一致，不可预约');
                }
            }
            $is_schoolfriend = $this->model->where(['applier_id'=>$params['applier_id'],'admission_starttime'=>$params['admission_starttime']])->find();
            if(!empty($is_schoolfriend)){
                $this->error('该时间段已有预约不可重复预约');
            }

            if(date('H')>19 || intval(date('H'))<8){
                $params['is_sendmessage'] = 1;
            }else{
                $params['is_sendmessage'] = 0;
            }
            $params['is_schoolfriend'] = 1;
            $sx_arr = [
                'create_time'   => $params['create_time'],
                'update_time'   => $params['create_time'],
                'applier_id'    => $params['applier_id'],
                'applier_name'  => $params['nickname'].'(校友随行人)',
                'reception_id'  => $params['reception_id'],
                'reception_name'=> $params['reception_name'],
                'admission_starttime'=> $params['admission_starttime'],
                'admission_endtime'=> $params['admission_endtime'],
                'is_schoolfriend'=> $params['is_schoolfriend'],
                'is_sendmessage'=> $params['is_sendmessage'],
                'memo'=>'校友随行人陪同返校',
            ];
            if($params['sx1']==1){
                $sx = $this->request->post("sx/a");
                if(!empty($sx[1]['nickname']) && !empty($sx[1]['tel']) && !empty($sx[1]['card_id'])){
                    $sx1 = [
                        'nickname'      => $sx[1]['nickname'],
                        'tel'           => $sx[1]['tel'],
                        'card_id'       => $sx[1]['card_id'],
                        'work_unit'     => $sx[1]['work_unit'],
                    ];
                    $sx1 = array_merge($sx_arr,$sx1);
                    Db::name('outsideschool')->insert($sx1);
                }
            }
            if($params['sx2']==1){
                $sx = $this->request->post("sx/a");
                if(!empty($sx[2]['nickname']) && !empty($sx[2]['tel']) && !empty($sx[2]['card_id'])){
                    $sx2 = [
                        'nickname'      => $sx[2]['nickname'],
                        'tel'           => $sx[2]['tel'],
                        'card_id'       => $sx[2]['card_id'],
                        'work_unit'     => $sx[2]['work_unit'],
                    ];
                    $sx2 = array_merge($sx_arr,$sx2);
                    Db::name('outsideschool')->insert($sx2);
                }
            }
            if($params['sx3']==1){
                $sx = $this->request->post("sx/a");
                if(!empty($sx[3]['nickname']) && !empty($sx[3]['tel']) && !empty($sx[3]['card_id'])){
                    $sx3 = [
                        'nickname'      => $sx[3]['nickname'],
                        'tel'           => $sx[3]['tel'],
                        'card_id'       => $sx[3]['card_id'],
                        'work_unit'     => $sx[3]['work_unit'],
                    ];
                    $sx3 = array_merge($sx_arr,$sx3);
                    Db::name('outsideschool')->insert($sx3);
                }
            }
            unset($params['sx1'],$params['sx2'],$params['sx3'],$params['card']);
            $params['memo'] = '校友返校';
            $res = $this->model->allowField(true)->save($params);
            if ($res){
                // 20:00-7:00不发短信
                if(intval(date('H'))>7 && date('H')<20){
                    if($reception_info -> sid){
                        $sid_arr = explode(',',$reception_info->sid);
                        foreach($sid_arr as $key => $v){
                            send_wechat_work_msg([$v], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                        }
                        $sf_sid_arr = explode(',',$reception_info->sf_sid);
                        foreach($sf_sid_arr as $key => $v){
                            send_wechat_work_msg([$v], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                        }
                        // 社会合作处
                        if($reception_info->id!=60){
                            // 校友申请给，于宁老师，张正明老师发送企业微信
                            send_wechat_work_msg([200201092], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                            send_wechat_work_msg([199501036], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                        }
                    }
                }

                $this->success('登记成功', '', ['nickname' => $params['nickname']]);
            }else{
                $this->error('登记失败');
            }
        }
        $title = '入校登记';
        $this->assign('pageTitle', $title);

        // 测试短信发送
        // $aaa = $this->request->get('aaa');
        // if(!empty($aaa)){
        //     $sm = '【青岛农业大学】亲爱的贾校友,您的入校申请已审核,欢迎您回母校!';
        //     $sm_url = 'http://api.qirui.com:7891/mt?dc=8&un=1267770012&pw=67d0eddeaf4c9ad2dcd0&sm='.$sm.'&da=18661473759&tf=3&rf=2&rd=0';
        //     echo $sm_url."<br/>";
        //     $data=  file_get_contents($sm_url);
        //     echo $data."<br/>";
        //     exit('完成');
        // }
        
        //获取参数，效验
        $appid = $this->request->get('appid');
        if(empty($appid)){
            $this->error('请先注册校友信息，再进行预约');
        }
        // 刘俊豪 在读研究生
        if($appid=='201140'){
            $this->error('在校生请使用校园卡入校');
        }
        if($appid!='252453'){
            echo "校友入校预约正在优化中<br/>";
            echo "请优先使用电子校友卡入校。。。。<br/>";
            echo "校友服务大厅->电子校友卡，将此页面出示给门卫即可。";
            die();
        }
        if($appid=='252453'){
            echo phpinfo();
            die();
        }
        $timestamp = $this->request->get('timestamp');
        $nonceStr = $this->request->get('nonceStr');
        $signature = $this->request->get('signature');

        if(!isset($appid) || !isset($timestamp) || !isset($nonceStr) || !isset($signature)){
            $this->error('参数错误');
        }
        $api_key = '1kNLken6UAHzW54CQsKyB3ubl5BznTtd';

        $data = [
            'timestamp' => $timestamp,
            'appid' => $appid,
            'api_key' => $api_key,
            'nonceStr' => $nonceStr
        ];
        $s_data = $this->asc_sort($data);
        $sign=sha1($s_data);

        if($sign!=$signature) {
            $insert_log = [
                'APPLIER_ID'=>$appid,
                'timestamp'=>$timestamp,
                'nonceStr'=>$nonceStr,
                'signature'=>$signature,
                'sign'=>$sign,
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            Db::name('school_friend_log')->insert($insert_log);
            $this->error('验证校友失败');
        }
        //获取参数，效验end
        
        $info = $this->_Schoolfriend($appid);//Db::name('school_friend')->where(['APPLIER_ID'=>$appid])->find();
        if(empty($info)){
            $insert_log = [
                'APPLIER_ID'=>$appid,
                'timestamp'=>$timestamp,
                'nonceStr'=>$nonceStr,
                'signature'=>$signature,
                'sign'=>$sign,
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            Db::name('school_friend_log')->insert($insert_log);
            $this->error('无校友记录，请联系学校校友工作办公室核实。');
        }
        $this->assign('info', $info[0]);
        $this->assignConfig('appids', $appid);
        $this->assign('starttime',date('Y/m/d',strtotime('+2 day')));
        return $this->fetch();
    }


    /**
     * 
     * [_Schoolfriend description]
     * @return [type] [description]
     */
    protected function _Schoolfriend($appid = null)
    {
        $data = [];
        $dbconn=oci_connect('user_xyb_xy','QauXybXy12#$',"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.8.16.80)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=icdc)))","UTF8");
        if (!$dbconn) {
           echo '连接失败';
           die();
        }
        $sql="select * from icdc_ods.view_xyb_xy_wlryrxxx where APPLIER_ID='".$appid."'";
        $data = $this -> exec($dbconn,$sql);
        return $data;
    }

    protected function exec($dbconn = null, $sql = ''){
        $stid = oci_parse($dbconn, $sql); // 配置SQL语句，准备执行
        if (!$stid) {
            $e = oci_error($dbconn);
            print htmlentities($e['message']);
            exit;
        }
        $r = oci_execute($stid, OCI_DEFAULT); // 执行SQL。OCI_DEFAULT表示不要自动commit
        if(!$r) {
            $e = oci_error($stid);
            echo htmlentities($e['message']);
            exit;
        }


        oci_fetch_all($stid,$data);

        $insertData = [];
        foreach ($data as $k => $v){
            foreach ($v as $kk => $vv){
                $insertData[$kk][$k] = $vv;
            }
        }
        return $insertData;
    }


    /**
     * ascii码从小到大排序
     * [asc_sort description]
     * @param  array  $params [description]
     * @return [type]         [description]
     */
    function asc_sort($params = array())
    {
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }


}
